<?php
namespace app\index\controller;

class Publish {
	public function index() {
		return view('index/publish');
	}

	public function addContent() {
		$content = input('post.content');
		$if_at = input('post.if_at');
		$at_list = input('post.at_list/a');
		$user_id = input('session.user_id');
		if ($user_id != null and $content != null) {
			$ctext = model('Text');
			$cuser = model('User');
			$texts_data = $ctext::where('uid', $user_id)->select();
			$count = 0;
			if ($texts_data != null) {
				foreach ($texts_data as $text) {
					if (substr($text->create_time, 0, 10) == date('Y-m-d')) {
						$count++;
					}
				}
			}
			if ($count <= 8) {
				$ctext->data([
					'uid' => $user_id,
					'content' => $content
				]);
				$ctext->save();
				$cuser::where('id', $user_id)->setInc('heat', 10);
				// 添加 @ 信息
				if ($if_at == 'true') {
					$this->addAtList($at_list, $ctext->id);
				}
				return json([
	                'status' => 'success',
	                'message' => '提交成功！',
	                'data' =>  '/index'
	            ]);
			}
			else {
				return json([
	                'status' => 'error',
	                'message' => '每日最多发布8条内容！',
	                'data' =>  null
	            ]);
			}
		}
		// 未接收到数据
		else {
			return json([
                'status' => 'error',
                'message' => '提交错误，请重试！',
                'data' =>  null
            ]);
		}
	}

	public function uploadImage() {
		$image_file = input('file.image');
		if ($image_file) {
			$image = $image_file->move(IMAGE_PATH);
			if ($image) {
				$image_name = strtr($image->getSaveName(), "\\", "/");
				return json([
					'status' => 'success',
					'message' => '上传成功！',
					'data' => $image_name
				]);
			}
			else {
				return json([
					'status' => 'error',
					'message' => '上传失败！',
					'data' => $image->getError()
				]);
			}
		}
		else {
			return json([
				'status' => 'error',
				'message' => '未接收到数据！',
				'data' => $image->getError()
			]);
		}
	}

	public function getAllUsers() {
		$cuser = model('User');
		$user_data = $cuser::field('id, fullname, avator_path')->select();
		return json([
            'status' => 'success',
            'message' => '获取成功！',
            'data' =>  $user_data
        ]);
	}

	private function addAtList($at_list, $sender_id) {
		$cmsglist = model('Msglist');
		$data_list = array();
		foreach ($at_list as $at) {
			$data = array();
			$data['sender'] = $sender_id;
			$data['receiver'] = $at;
			$data['type'] = 1;
			array_push($data_list, $data);
		}
		$cmsglist->saveAll($data_list);
	}
}

			// $img_num = substr_count($content, '<img');
			// if ($img_num > 3) {
			// 	return json([
	  //               'status' => 'error',
	  //               'message' => '每条内容最多能够使用3张图片！',
	  //               'data' =>  null
	  //           ]);
			// }